/*
 * @author Ashish Tomar
 */

package DocClass;


import org.w3c.dom.*;
import javax.xml.parsers.*;
import org.xml.sax.*;


public class ResultParser {

	/**
	 * Parse the XML results of a query to Yahoo BOSS, and extract the information
	 * used by this application.
	 * @param result The XML string returned by a BOSS query.
	 * @return A ResultSet object containing a distinct DocumentSet object for
	 * each result in the query.
	 */
	public ResultSet addResult(String result)
	{


		ResultSet re=null;

		try{
			DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
			DocumentBuilder db = factory.newDocumentBuilder();
			InputSource inStream = new InputSource();
			inStream.setCharacterStream(new java.io.StringReader(result));
			Document doc = db.parse(inStream);




			NodeList nodes = doc.getElementsByTagName("result");
			int nodesl=nodes.getLength();
			re = new ResultSet(nodes.getLength());

			for (int i = 0; i < nodesl; i++) {
				Element element = (Element) nodes.item(i);

				NodeList url = element.getElementsByTagName("url");
				Element line = (Element) url.item(0);

				re.doc[i].URL=getCharacterDataFromElement(line);


				NodeList title = element.getElementsByTagName("title");
				line = (Element) title.item(0);

				re.doc[i].Title=getCharacterDataFromElement(line);


				NodeList abstrac = element.getElementsByTagName("abstract");
				line = (Element) abstrac.item(0);

				re.doc[i].Abstract=getCharacterDataFromElement(line);

			}




		}
		catch (Exception e) {
			throw new RuntimeException(e);
		}
		return re;
	}
	/**
	 * Extract the character data from an XML element, strip it of emphasis
	 * tags, and return it as a string.
	 * @param e the XML element in question.
	 * @return the character data of this element, with HTML tags stripped.
	 */
	protected static String getCharacterDataFromElement(Element e) {
		Node child = e.getFirstChild();
		if (child instanceof CharacterData) {
			CharacterData cd = (CharacterData) child;
			String tmp = cd.getData();
			return tmp.replaceAll("<(/?)b>", "");
		}
		return "?";
	}

}
